<template>
  <div class="main-box">
    <el-page-header :title="$t('title.back')" @back="goBack" :content="$t('title.editApp')"> </el-page-header>
    <el-row class="pull-right">
      <el-button size="medium" @click="goBack">{{ $t('btnText.cancel') }}</el-button>
      <el-button size="medium" type="primary" @click="submitEdit('editApp')">{{ $t('btnText.save') }}</el-button>
    </el-row>
    <el-form class="content-box" ref="editApp" :model="formData" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="6">
          <el-form-item class="labelWith50" prop="icon">
            <el-input :size="size" v-model="formData.icon" autocomplete="off" style="display: none"></el-input>
            <div
              class="icon-box"
              @click="
                dialogIcon.selected = formData.icon;
                dialogIcon.visible = true;
              "
            >
              <div class="icon-content" v-if="formData.icon != ''">
                <i :class="formData.icon" :style="iconColor"></i>
              </div>
            </div>
          </el-form-item>
          <el-form-item :label="$t('label.iconColor')" prop="iconColor">
            <el-color-picker v-model="formData.iconColor" size="mini"></el-color-picker>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('label.platformType')" prop="platformType">
                <el-select
                  :size="size"
                  v-model="formData.platformType"
                  :placeholder="$t('placeholder.pleaseSelect')"
                  prop="platformType"
                >
                  <template v-for="(item, index) in types">
                    <el-option :key="index" :label="item.label" :value="item.value"></el-option>
                  </template>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item :label="$t('label.chName')" prop="chName">
                <el-input
                  size="medium"
                  v-model="formData.chName"
                  :placeholder="$t('placeholder.zhName')"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('label.enName')" prop="enName">
                <el-input
                  size="medium"
                  v-model="formData.enName"
                  :placeholder="$t('placeholder.enName')"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('label.typeId')" prop="typeId">
                <el-select
                  :size="size"
                  v-model="formData.typeId"
                  :placeholder="$t('placeholder.pleaseSelect')"
                  prop="typeId"
                >
                  <template v-for="(item, index) in appCategorys">
                    <el-option :key="index" :label="item.label" :value="item.value"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('label.description')" prop="description">
                <el-input
                  size="medium"
                  v-model="formData.description"
                  :placeholder="$t('placeholder.description')"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <div class="pachytene"></div>
      <el-form-item :label="$t('label.version')" prop="version">
        <el-input
          size="medium"
          v-model="formData.version"
          :placeholder="$t('placeholder.version')"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('label.urlPc')"
        prop="urlPc"
        v-if="formData.platformType === 1 || formData.platformType === 2"
      >
        <el-input
          size="medium"
          v-model="formData.urlPc"
          :placeholder="$t('placeholder.urlPc')"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('label.urlApp')"
        prop="urlApp"
        v-if="formData.platformType === 1 || formData.platformType === 3"
      >
        <el-input
          size="medium"
          v-model="formData.urlApp"
          :placeholder="$t('placeholder.urlApp')"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('label.meteringJson')" prop="meteringJson">
        <el-input
          size="medium"
          v-model="formData.meteringJson"
          type="textarea"
          :placeholder="$t('placeholder.meteringJson')"
          autocomplete="off"
          style="display: none"
        ></el-input>
        <vue-json-editor v-model="jsonObj" :showBtns="false" :mode="'code'" />
      </el-form-item>
    </el-form>

    <!-- 图标选择窗口 -->
    <el-dialog
      :title="$t('dialog.icons.title')"
      :visible.sync="dialogIcon.visible"
      width="600px"
      :close-on-click-modal="dialogIcon.closeOnClickModal"
      :close-on-press-escape="dialogIcon.closeOnPressEscape"
      append-to-body
      element-loading-background="rgba(0, 0, 0, 0.5)"
      @close="closeDialogIcon"
    >
      <el-radio v-for="(item, index) in dialogIcon.data" :key="index" v-model="dialogIcon.selected" :label="item"
        ><i :class="item"></i
      ></el-radio>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogIcon.visible = false">{{ $t('btnText.cancel') }}</el-button>
        <el-button size="medium" type="primary" @click="selectedIcon">{{ $t('btnText.ok') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategorys, appEdit, getAppDetail } from '../../api/api';
import { errorCode } from '@/utils/index';
import vueJsonEditor from 'vue-json-editor';
export default {
  name: 'edit',
  props: {
    target: {
      type: Number,
      default: 0
    }
  },
  components: {
    vueJsonEditor
  },
  data() {
    return {
      size: 'medium',
      appCategorys: [],
      jsonObj: null,
      formData: {
        id: 0,
        chName: '',
        description: '',
        enName: '',
        icon: '',
        iconColor: '',
        meteringJson: '',
        operator: '',
        platformType: 1,
        typeId: '',
        urlApp: '',
        urlPc: '',
        version: ''
      },
      dialogIcon: {
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: null,
        data: [
          'iconfont iconkucunguanli-01',
          'iconfont iconkehuguanli-01',
          'iconfont iconyingyongguanli-01',
          'iconfont iconzuzhijigou-01',
          'iconfont iconyonghuguanli-01',
          'iconfont iconjiaoseguanli-01',
          'iconfont iconweixiubaoyang-01',
          'iconfont iconzutaiguanli-01',
          'iconfont iconwumoxingguanli-01',
          'iconfont iconwangguanguanli-01',
          'iconfont iconshebeiguanli-01',
          'iconfont iconcaozuorizhi-01',
          'iconfont iconyujingtixing-01',
          'iconfont iconlishishuju-01',
          'iconfont iconshishishuju-01',
          'iconfont iconGISditu-01',
          'iconfont iconyingyongshangcheng-01'
        ],
        selected: null
      }
    };
  },
  computed: {
    types() {
      return [
        { label: this.$t('appTypes[1]'), value: 1 },
        { label: this.$t('appTypes[2]'), value: 2 },
        { label: this.$t('appTypes[3]'), value: 3 }
      ];
    },
    rules() {
      return {
        icon: [{ required: true, trigger: 'change', message: this.$t('error.icon') }],
        iconColor: [{ required: true, trigger: 'change', message: this.$t('error.iconColor') }],
        platformType: [{ required: true, trigger: 'change', message: this.$t('error.platformType') }],
        chName: [
          { required: true, trigger: 'blur', message: this.$t('error.chName') },
          { validator: this.validateChName, trigger: 'blur', message: this.$t('error.chName') }
        ],
        enName: [
          { required: true, trigger: 'blur', message: this.$t('error.enName') },
          { validator: this.validateEnName, trigger: 'blur', message: this.$t('error.enName') }
        ],
        description: [{ validator: this.validateDescription, trigger: 'blur', message: this.$t('error.description') }],
        typeId: [{ required: true, trigger: 'change', message: this.$t('error.typeId') }],
        version: [
          { required: true, trigger: 'blur', message: this.$t('error.version') },
          { validator: this.validateVersion, trigger: 'blur', message: this.$t('error.version') }
        ],
        urlPc: [{ required: true, trigger: 'blur', message: this.$t('error.urlPc') }],
        urlApp: [{ required: true, trigger: 'blur', message: this.$t('error.urlApp') }],
        meteringJson: [{ validator: this.validateJson, trigger: 'blur', message: this.$t('error.meteringJson') }]
      };
    },
    iconColor() {
      return `color: ` + this.formData.iconColor;
    }
  },
  watch: {
    jsonObj: {
      handler(n, o) {
        if (n) {
          this.$nextTick(() => {
            this.formData.meteringJson = JSON.stringify(n);
          });
        }
      },
      immediate: true
    }
  },
  created() {
    this.getCategorys();
    this.getAppDetail();
  },
  methods: {
    validateChName(rule, value, callback) {
      let myreg = /^[\u4e00-\u9fa50-9]{2,12}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t('error.chName')));
      }
      callback();
    },
    validateEnName(rule, value, callback) {
      let myreg = /^[a-zA-Z0-9]{4,20}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t('error.enName')));
      }
      callback();
    },
    validateDescription(rule, value, callback) {
      let myreg = /^[\u4e00-\u9fa5]{4,16}$/;
      if (!myreg.test(value) && value !== '') {
        callback(new Error(this.$t('error.description')));
      }
      callback();
    },
    validateVersion(rule, value, callback) {
      let myreg = /^[a-zA-Z0-9.]{2,10}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t('error.version')));
      }
      callback();
    },
    validateJson(rule, value, callback) {
      if (value === '') {
        callback();
      } else {
        try {
          let obj = JSON.parse(value);
          if (typeof obj === 'object' && obj) {
            callback();
          } else {
            callback(new Error(this.$t('error.meteringJson')));
          }
        } catch (e) {
          callback(new Error(this.$t('error.meteringJson')));
        }
      }
    },
    closeDialogIcon() {
      this.dialogIcon.selected = null;
    },
    selectedIcon() {
      this.formData.icon = this.dialogIcon.selected;
      this.dialogIcon.visible = false;
    },
    goBack() {
      this.$emit('toChangeComponentName', 'detail');
    },
    getCategorys() {
      this.appCategorys = [];
      getCategorys({}).then(res => {
        for (let item of res.data) {
          let obj = {
            label: item.name,
            value: item.id
          };
          this.appCategorys.push(obj);
        }
      });
    },
    getAppDetail() {
      getAppDetail({ id: this.target }).then(res => {
        for (let p in res.data) {
          this.formData[p] = res.data[p];
        }
        try {
          let obj = JSON.parse(this.formData.meteringJson);
          if (typeof obj === 'object' && obj) {
            this.jsonObj = obj;
          } else {
            this.jsonObj = {};
          }
        } catch (e) {
          this.jsonObj = {};
        }
      });
    },
    submitEdit(formName) {
      console.info(formName);
      this.$refs[formName].validate(valid => {
        if (valid) {
          let platformType = this.formData.platformType;
          if (platformType === 2) {
            this.formData.urlApp = '';
          } else if (platformType === 3) {
            this.formData.urlPc = '';
          }
          appEdit(this.formData).then(res => {
            this.$message.success(errorCode(res.message));
            this.goBack();
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.main-box {
  position: relative;
  color: #606266;
  height: 100%;
  background-color: #ffffff;
}
.content-box {
  height: calc(100% - 57px);
  overflow: auto;
  padding: 20px;
}
.el-select,
.el-input {
  width: 100% !important;
}
.el-page-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}
.pull-right {
  position: absolute;
  top: 10px;
  right: 20px;
}
.icon-box {
  width: 148px;
  height: 148px;
  border: 1px dashed #dcdfe6;
  box-sizing: border-box;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fafafa;
  background-image: url('../../assets/Union.png');
  background-repeat: no-repeat;
  background-position: center;
  padding: 15px;
}
.icon-content {
  display: inline-block;
  width: 100%;
  height: 100%;
  background-color: #fafafa;
  font-size: 116px;
}
.iconfont {
  line-height: 1;
  font-size: 100%;
}
.el-radio {
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 50px;
  height: 50px;
  vertical-align: middle;
  padding: 5px;
  margin-bottom: 30px;
}
::v-deep .el-radio .el-radio__input {
  display: none;
}
::v-deep .el-radio .el-radio__label {
  padding-left: 0;
}
::v-deep .el-radio .el-radio__label i {
  font-size: 40px;
}
.el-radio.is-checked {
  border-color: var(--color-primary);
  box-shadow: 0 0 5px var(--color-primary);
}
.labelWith50 + ::v-deep .el-form-item .el-form-item__label {
  width: 70px;
  margin-left: 70px;
  text-align: left;
  line-height: 28px;
}
.labelWith50 + ::v-deep .el-form-item .el-form-item__content {
  margin-left: 70px !important;
  height: 28px;
  line-height: 28px;
}
.labelWith50 ::v-deep .el-form-item__label {
  width: 70px !important;
}
.labelWith50 ::v-deep .el-form-item__content {
  margin-left: 70px !important;
}
.pachytene {
  height: 6px;
  background: #f2f6fc;
  margin-bottom: 20px;
}
::v-deep .el-textarea__inner {
  height: 200px;
  resize: none;
}
</style>
